<template>
	<view class="xunshi-box">
		<navBar title="施工巡视记录" @goBack="uni.navigateBack()"></navBar>

		<view class="space-box"></view>
		<view class="fill-report">
			<view class="form">
				<view  class="form-item">
					<view class="label">项目名称</view>
					<view class="form-content">
						<view class="form-text">{{ detailInfo.pmName }}</view>
					</view>
				</view>
				<view  class="form-item">
					<view class="label">施工桩号</view>
					<view class="form-content">
						<view class="form-text">{{ detailInfo.code }}</view>
					</view>
				</view>
				<view  class="form-item">
					<view class="label">桩长</view>
					<view class="form-content">
						<view class="form-text">{{ detailInfo.pileLength ? `${detailInfo.pileLength}m` : '' }}</view>
					</view>
				</view>
				<view  class="form-item">
					<view class="label">深度</view>
					<view class="form-content">
						<view class="form-text">{{ detailInfo.overallElevation ? `${detailInfo.overallElevation}m` : '' }}</view>
					</view>
				</view>
			</view>
			<view class="txt-title">
				<view class="txt black">现场情况记录</view>
				<view class="txt blue" @click="addRecord" v-if="state !== '已填报'">新增记录</view>
			</view>
			<view class="add-box" v-for="(item, index) in addList" :key="index">
				<view class="txt-time">{{ getDate2(item.inspectorTime) }} 巡视</view>
				<view class="txt-label">巡视人员：{{ item.createUserName }}</view>
				<view class="btn-box" style="padding-top: 24rpx;">
					<view class="btn none">{{ item.siteState || '' }}</view>
					<view class="btn-box" v-if="state !== '已填报'">
						<view class="btn red" @click="delRecord(index)" >删除</view>
						<view class="btn blue" @click="editRecord(index)">编辑</view>
					</view>
					<view class="btn-box" v-else>
						<view class="btn blue" @click="editRecord(index)">详情</view>
					</view>
				</view>
			</view>
			<u-empty  v-if="!addList.length"  mode="data" text="暂无数据"  icon="http://cdn.uviewui.com/uview/empty/data.png"></u-empty>
			<view class="footer-button" v-if="state !== '已填报'">
				<view class="button-placeholder"></view>
				<view class="button-group">
					<button @click="clickSubmit(true)" :loading="isLoading" class="button-gray">保存</button>
					<button @click="clickSubmit(false)" :loading="isLoading" class="button-primary">提交</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapGetters } from "vuex";
	import { getSystemHeightInfo, isPositiveInteger, imgFun, getFormCheckResult } from "@/utils/common.js";
	import { handleFormatDate, compareDate } from "@/utils/date.js";
	import fileMixin from "@/mixins/file.js";
	import mixins from "@/utils/mixins.js"
	import signature from "@/subpackage-mjs/pages/comoponents/signature.vue";
	import { uploadFile } from '@/utils/request'
	import { getPicture, deleteImg, doc_deleteAttachs } from '@/api/doc.js'
	import { mjsProject_list,mjsConstructionInspectionRecord_get, mjsConstructionInspectionRecord_save } from "@/api/mjs.js"
	export default {
		name: "add-new-record",
		mixins: [fileMixin, mixins],
		props: {},
		components: {
			signature
		},
		data() {
			return {
				// 容器之外的高度
				containerOutsideHeight: 0,
				timeVal: Number(new Date()),
				// 填报表单
				fillForm: {},
				// 是否在加载中
				isLoading: false,
				addList: [],
				detailInfo:{},
				state:'',
				taskState:{
					'开始':'field_situation_begin',
					'施工中':'field_situation_under_construction',
					'已完工':'field_situation_completed'
				}
			}
		},
		computed: {
			...mapGetters(['dictMap'])
		},
		watch: {},
		mounted() {
			this.initContainerData();
			uni.$off('sendFormInfo')
			uni.$on('sendFormInfo', result => {
				console.log(result, '接受')
				// result.siteStateName = this.getName(this.$store.getters.dictMap['field_situation'], result.siteState)
				if(!result.isUpdate && !('id' in result)) {
					this.addList.push(result)
				} else {
					this.$set(this.addList, this.recordIndex, result)
				}
			})
		},
		onLoad(op) {
			console.log(op, '123')
			if(op) {
				this.mjsDailyMissionId = op.id
				this.pbId = op.pbId
				this.updateId = op.updateId
				this.state = op.state
				this.getDetailById(op.id,op.pbId,op.updateId)
			}
		},
		methods: {
			getName(arr,code) {
				let name = ''
				if (arr && arr.length > 0) {
					name = arr.find(it => it.code == code) ? arr.find(it => it.code == code).name : ''
				}
				return name
			},
			async getItemImage(docId) {
				return await new Promise((resolve, reject) => {
					getPicture({
						docId
					}).then(res => {
						resolve(res.result.map(it => ({
							url: this.$config.IMG_FILE_URL + it.fileName,
							id: it.id
						})) || []);
					}).catch(err => reject(err))
				})
			},
			getDetailById(id,pbId, updateId) {
				if(!updateId) updateId = undefined
				mjsConstructionInspectionRecord_get({mjsDailyMissionId:id,pbId, id:updateId}).then(res => {
					console.log(res, '详情')
					
					this.detailInfo = {...res.result}
					if(res.result.fieldNotes) {
						this.addList = res.result.fieldNotes.map(it => ({
							...it,
							singlePileWorkload:res.result.singlePileWorkload,
							waterCementRatio:res.result.waterCementRatio,
							mudWeight:res.result.mudWeight,
						}))
						console.log(this.addList)
					}
				})
			},
			/** 初始化容器数据 */
			initContainerData() {
				const { stateHeight, bottomHeight, navbarHeight } = getSystemHeightInfo();
				this.containerOutsideHeight = stateHeight + bottomHeight + navbarHeight + 70;
			},
			addRecord() {
				// console.log(uni.getStorageSync('recordInfo'), this.pbId)
				// console.log(uni.getStorageSync('recordInfo').pbId != this.pbId, '判断')
				if(uni.getStorageSync('recordInfo') && uni.getStorageSync('recordInfo').pbId != this.pbId) {
					uni.removeStorageSync('recordInfo')
				}
				uni.navigateTo({
					url:`/subpackage-mjs/pages/constructionInspectionRecord/addDetail?projectPbId=${this.pbId}`
				})
			},
			delRecord(index) {
				this.addList.splice(index, 1)
			},
			editRecord(index) {
				if(this.state == '已填报') {
					this.addList[index].disabled = true
				}else {
					this.addList[index].disabled = false
				}
				this.recordIndex = index
				this.addList[index].isUpdate = true
				uni.navigateTo({
					url:'/subpackage-mjs/pages/constructionInspectionRecord/addDetail',
					success: res => {
						res.eventChannel.emit('sendDataList', {
							data: this.addList[index] || {}
						})
					}
				})
			},
			getCode(arr,name) {
				let code = ''
				if (arr && arr.length > 0) {
					code = arr.find(it => it.name == name) ? arr.find(it => it.name == name).code : ''
				}
				return code
			},
			/** 保存每日交底填报的内容 */
			handleSaveFilleport(bool) {
				let singlePileWorkload = undefined;
				let waterCementRatio = undefined;
				let mudWeight = undefined;
				if(uni.getStorageSync('recordInfo')) {
					let tempObj = uni.getStorageSync('recordInfo')
					singlePileWorkload = tempObj.singlePileWorkload
					waterCementRatio = tempObj.waterCementRatio
					mudWeight = tempObj.mudWeight
				}
				if(this.addList.length) {
					for(let item of this.addList) {
						if(item.overfallState == 0 || item.overfallState == '正常') {
							item.overfallState = 0
						}else if(item.overfallState == 1 || item.overfallState == '不正常'){
							item.overfallState = 1
						}
						if(item.orificesState == 0 || item.orificesState == '是') {
							item.orificesState = 0
						}else if(item.orificesState == 1 || item.orificesState == '否'){
							item.orificesState = 1
						}
						if(item.id) {
							item.id = undefined
						}
					}
				}
				return new Promise(resolve => {
					let resq = {
						id:this.detailInfo.id ? this.detailInfo.id : undefined,
						mjsDailyMissionId:this.mjsDailyMissionId,
						pbId:this.detailInfo.pbId,
						singlePileWorkload, //单桩工作量
						waterCementRatio, //每桩-水灰比
						mudWeight, //每桩-泥浆比重
						isSave: bool, //是否保存
						fieldNotes:this.addList || []
					}
					mjsConstructionInspectionRecord_save(resq).then(res => {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 1000,
						});
						// this.initFillForm();
							setTimeout(() => {
								const pages = getCurrentPages();
								const prevPage = pages[pages.length - 2]; // 上一页实例
								uni.navigateBack({
									delta:1,
									success: () => {
										prevPage.$vm.search();
									}
								})
							}, 1200)
						
						resolve();
					});
				});
			},
			isLastTimeLargest(arr) {
				const lastTime = arr[arr.length - 1].inspectorTime
				return arr.every(obj => new Date(obj.inspectorTime).getTime() <= new Date(lastTime).getTime())
			},
			/** 点击提交按钮 */
			async clickSubmit(bool) {
				// console.log(this.addList, '数组')
				
				// 表单校验...
				if(!this.addList.length) return this.$message('现场情况记录不能为空！')
				if(!bool) {
					if(this.addList.length && this.addList[this.addList.length - 1].siteState !== '已完工') {
						return this.$message('提交失败！现场情况为已完工时才能提交')
					}
					if(!this.isLastTimeLargest(this.addList)) {
						return this.$message('最新的巡视记录时间不得小于其他记录时间！')
					}
				}
				// return
				// 调用接口...
				if (!this.isLoading) {
					this.isLoading = true;
					await this.handleSaveFilleport(bool);
					this.isLoading = false;
				}
			},

			/** 初始化表单 */
			initFillForm() {
			
			},

		}
	}
</script>

<style scoped lang="scss">
	.xunshi-box {
		/* #ifdef MP-WEIXIN */
		padding-top: 200rpx;
		/* #endif */
	}
	.fill-report {
		.form {
			background: #fff;
			padding-top: 26upx;

			.form-item {
				height: 100upx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin: 0 30upx;
				border-bottom: 1px solid #e2e5ed;

				&:last-of-type {
					border-bottom: none;
				}

				.label {
					color: #445469;
					line-height: 44upx;
					flex-shrink: 0;
					font-weight: 500;
					font-size: 32rpx;
				}

				.form-content {
					color: #22204e;
					display: flex;
					align-items: center;
				}

				.form-text {
					line-height: 58upx;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					max-width: 302upx;
					color: #22204E;
					font-weight: 500;
					font-size: 32rpx;
				}

				.form-text.none {
					opacity: .7;
					font-size: 30rpx;
				}

				.u-icon {
					margin-left: 40upx;
				}

				.uicon-close-circle-fill {
					margin-left: 32upx;
				}

				.u-input {
					width: 340upx;
					text-align: right;

					::v-deep .u-input__content__field-wrapper {
						margin-right: 24upx;
					}

					::v-deep .uni-input-wrapper {
						text-align: right;
					}
				}

				.u-switch {
					margin-right: 30upx;
				}
			}

			.no-inline {
				display: block;
				height: auto;

				.label {
					line-height: 100upx;
				}
			}
		}


	}

	.txt-title {
		padding: 0 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 100rpx;
		line-height: 100rpx;
		background-color: #F5F7FA;

		.txt {
			font-size: 36rpx;
			font-weight: 600;

			&.black {
				color: #22204E;
			}

			&.blue {
				font-size: 32rpx;
				color: #2F80ED;
			}
		}
	}

	.add-box {
		margin: 30rpx 20rpx 0px 30rpx;
		border-bottom: 2rpx dashed #E0E7F6;
		padding-bottom: 20rpx;

		.txt-time {
			font-weight: 600;
			font-size: 32rpx;
			color: #22204E;
		}

		.txt-label {
			font-weight: 500;
			font-size: 28rpx;
			color: #6A819E;
			padding-top: 8rpx;
		}

		.btn-box {
			display: flex;
			align-items: center;
			justify-content: space-between;
			
			.btn {
				width: 64px;
				height: 30px;
				border-radius: 4px;
				line-height: 30px;
				text-align: center;
				color: #fff;

				&.none {
					border: 1px solid #2F80ED;
					color: #2F80ED;
				}

				&.red {
					background: #FF6A6A;
				}

				&.blue {
					margin-left: 20rpx;
					background: #2F80ED;
				}
			}

		}
	}

	.fill-report.mar-t {
		padding-top: 26upx;
	}

	.footer-button {
		height: 154upx;

		.button-placeholder {
			height: 100%;
		}

		.button-group {
			height: 154upx;
			padding: 30rpx 0 30rpx 0;
			box-sizing: border-box;
			background: #fff;
			position: fixed;
			// width: 100vw;
			bottom: -30rpx;
			z-index: 11;

			.button-primary {
				background: #2f80ed;
				border-radius: 4upx;
				color: #fff;
				font-weight: bold;
				line-height: 92upx;
				text-align: center;
			}
			.button-gray {
				background: #EBEBEB;
				border-radius: 4upx;
				color: #445469;
				font-weight: bold;
				line-height: 92upx;
				text-align: center;
				width: 100%;
			}
		}
	}

	.required {
		&::before {
			content: "*";
			color: #ff6a6a;
		}
	}

	.space-box {
		background-color: #f5f7fb;
		height: 40rpx;
	}
</style>